<template>
	<div id="vditor"></div>
</template>

<script lang="ts">
import Vditor from 'vditor';
import 'vditor/dist/index.css';
import { useNoteStore } from '@/stores/noteStore';
import { useThemeStore } from '@/stores/themeStore';

export default defineComponent({
	name: 'Viditor',
	props: {
		modelValue: {
			type: String,
			required: true,
		},
	},
	emits: ['update:modelValue'],
	setup(props, { emit }) {
		const noteStore = useNoteStore();
		const themeStore = useThemeStore();

		// 编辑器实例
		const vditor = ref<Vditor>();

		// 编辑器主题
		const vditorTheme = computed<'classic' | 'dark'>(() => {
			return themeStore.theme === 'dark' ? 'dark' : 'classic';
		});
		watch(
			vditorTheme,
			(val: 'classic' | 'dark') => {
				vditor.value?.setTheme(val === 'dark' ? 'dark' : 'classic');
			},
			{ immediate: true }
		);

		// 编辑器内容
		const vditorContent = ref<string>(props.modelValue);
		watch(vditorContent, (val: string) => {
			emit('update:modelValue', val);
		});
		watch(
			() => noteStore.activeNote.id,
			() => {
				vditor.value?.setValue(noteStore.activeNote.content);
			}
		);

		onMounted(() => {
			// 初始化编辑器
			vditor.value = new Vditor('vditor', {
				height: '100%',
				cache: {
					enable: false,
				},
				input: (text: string) => {
					vditorContent.value = text;
				},
				theme: vditorTheme.value,
				value: vditorContent.value,
				toolbar: [
					'emoji',
					'headings',
					'bold',
					'italic',
					'link',
					'list',
					'ordered-list',
					'check',
					'outdent',
					'indent',
					'line',
					'code',
					'table',
					'edit-mode',
					'preview',
					'outline',
					'devtools',
					'fullscreen',
					'undo',
					'redo',
				],
			});
		});
	},
});
</script>

<style lang="scss" scoped>
#vditor {
	border: none;
}

#vditor * {
	transition: all 0.3s;
}

:deep(.vditor-toolbar) {
	display: flex;
	flex-wrap: wrap;
	align-items: center;
	padding: 0 !important;
	justify-content: center;
}
</style>
